#!/usr/bin/env sh

set -e

src=https://github.com/gomodule/redigo.git

cd $(dirname $0)

rm -rf tmp
mkdir -p tmp
git -C tmp clone ${src} .

rId=$(git -C tmp rev-parse HEAD)
sId=$(git -C tmp rev-parse --short HEAD)
rTag=$(git -C tmp describe --tags $(git -C tmp rev-list --tags --max-count=1))
rDesc=$(git -C tmp describe --tags ${rId})
rTime=$(git -C tmp show --pretty=format:"%ci" | sed -n '1p')

localId=$(cat sync.last | sed -n '1p')
localTag=$(cat sync.last | sed -n '2p')
localDesc=$(cat sync.last | sed -n '3p')
localTime=$(cat sync.last | sed -n '4p')

echo "remote commit id  : ${rId}"
echo "remote commit tag : ${rTag}"
echo "remote commit tid : ${rDesc}"
echo "remote commit time: ${rTime}"
echo
echo "local  commit id  : ${localId}"
echo "local  commit tag : ${localTag}"
echo "local  commit tid : ${localDesc}"
echo "local  commit time: ${localTime}"

if [ "$localId" != "${rId}" ]; then
    rm -f tmp/redis/*_test.go
    rm -f *.go
    mv tmp/redis/*.go .
    mv tmp/LICENSE .

    rm -rf tmp
    go mod tidy

    echo ${rId} >sync.last
    echo ${rTag} >>sync.last
    echo ${rDesc} >>sync.last
    echo ${rTime} >>sync.last

    sed -i "s/^提交编号.*/提交编号: ${rId}/g" readme.md
    sed -i "s/^提交标签.*/提交标签: ${rTag}/g" readme.md
    sed -i "s/^显示标签.*/显示标签: ${rDesc}/g" readme.md
    sed -i "s/^提交时间.*/提交时间: ${rTime}/g" readme.md
    sed -i "s/^同步时间.*/同步时间: $(date -R)/g" readme.md

    git add .
    git commit -m "同步: ${rDesc} ${sId} ${rTime}"
    git push -f -u origin main
fi

if [ "$localTag" != "${rTag}" ]; then
    git tag ${rTag}
    git push --tags
fi

rm -rf tmp
